﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.Widget;
using Android.Support.V7.App;
using Android.Views;
using Android.Widget;
using Medicine.Core.Listeners;

namespace Medicine.Activities
{

    public class QueryInfoBaseActivity : AppCompatActivity
    {
        protected ListView _listView;
        private Activity _children;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
        }

        public void SetInitControl(Activity activity,int viewId,int swipeRefreshId)
        {
            this._children = activity;
            _listView = FindViewById<ListView>(viewId);
            _listView.Adapter = new Models.MedicineAdapter(activity);

            _listView.ItemClick += OnListItemClick;
            _listView.ItemLongClick += OnItemLongClick;
            #region 下拉刷新
            var swipeRefreshLayout = FindViewById<SwipeRefreshLayout>(swipeRefreshId);
            swipeRefreshLayout.SetOnRefreshListener(new SwipeRefreshLayoutOnRefreshListener(swipeRefreshLayout, _listView));
            #endregion
        }

        protected void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            var listView = sender as ListView;
            var medicine = (listView.Adapter as Models.MedicineAdapter)[e.Position];

            CustomDialogs.ShowMedicineDetailDialog showMedicineDetailDialog = new CustomDialogs.ShowMedicineDetailDialog(this._children, medicine);
            showMedicineDetailDialog.Show();
        }



        protected void OnItemLongClick(object sender, AdapterView.ItemLongClickEventArgs e)
        {
            var listView = sender as ListView;
            var medicine = (listView.Adapter as Models.MedicineAdapter)[e.Position];

            Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(listView.Context);
            builder.SetMessage("确定删除?");
            builder.SetTitle("提示");

            builder.SetPositiveButton("确定", new EventHandler<DialogClickEventArgs>((s, e) =>
            {
                var adapter = (listView.Adapter as Models.MedicineAdapter);
                if (medicine != null)
                {
                    var result = DbContext.DbC.Delete(medicine);
                    if (result > 0)
                    {
                        adapter.NotifyDataSetChanged();
                        Helpers.MessageShow.ShowShortMsg(listView.Context, "删除成功");
                    }
                    else
                        Helpers.MessageShow.ShowShortMsg(listView.Context, "删除失败");
                }
            }));

            builder.SetNegativeButton("取消", new EventHandler<DialogClickEventArgs>((s, e) =>
            {

            }));

            builder.Create().Show();
        }
    }
}